package com.lecture.java8.graph.demo01;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileManager {

    private static final String VILLAGE_FILE = "D:\\study\\tmp\\villages.txt";
    private static final String ROAD_FILE = "D:\\study\\tmp\\roads.txt";

    public static List<Village> loadVillages() {
        List<Village> villages = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(VILLAGE_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 5) {
                    int id = Integer.parseInt(parts[0]);
                    String name = parts[1];
                    int x = Integer.parseInt(parts[2]);
                    int y = Integer.parseInt(parts[3]);
                    String desc = parts[4];
                    villages.add(new Village(id, name, x, y, desc));
                }
            }
        } catch (IOException e) {
            System.out.println("Error loading villages: " + e.getMessage());
        }
        return villages;
    }

    public static void saveVillages(List<Village> villages) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(VILLAGE_FILE))) {
            for (Village v : villages) {
                writer.write(v.id + "," + v.name + "," + v.x + "," + v.y + "," + v.description);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("Error saving villages: " + e.getMessage());
        }
    }

    public static List<Road> loadRoads() {
        List<Road> roads = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(ROAD_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    int startId = Integer.parseInt(parts[0]);
                    int endId = Integer.parseInt(parts[1]);
                    double length = Double.parseDouble(parts[2]);
                    roads.add(new Road(startId, endId, length));
                }
            }
        } catch (IOException e) {
            System.out.println("Error loading roads: " + e.getMessage());
        }
        return roads;
    }

    public static void saveRoads(List<Road> roads) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ROAD_FILE))) {
            for (Road r : roads) {
                writer.write(r.startId + "," + r.endId + "," + r.length);
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("Error saving roads: " + e.getMessage());
        }
    }
}
